#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

// 矩阵大小 - 可以调整来测试不同规模
#define ROWS 10000
#define COLS 10000

// 生成随机矩阵
void generate_random_matrix(double** matrix, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = (double)rand() / RAND_MAX * 100.0; // 0-100之间的随机数
        }
    }
}

// 按行相加
void matrix_add_row_wise(double** A, double** B, double** C, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
}

// 按列相加
void matrix_add_col_wise(double** A, double** B, double** C, int rows, int cols) {
    for (int j = 0; j < cols; j++) {
        for (int i = 0; i < rows; i++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
}

// 分配二维数组
double** allocate_matrix(int rows, int cols) {
    double** matrix = (double**)malloc(rows * sizeof(double*));
    for (int i = 0; i < rows; i++) {
        matrix[i] = (double*)malloc(cols * sizeof(double));
    }
    return matrix;
}

// 释放二维数组
void free_matrix(double** matrix, int rows) {
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
}


int matrices_equal(double** A, double** B, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (A[i][j] != B[i][j]) {
                return 0;
            }
        }
    }
    return 1;
}

int main() {
    // 初始化随机数种子
    srand((unsigned int)time(NULL));
    
    printf("矩阵大小: %d x %d\n", ROWS, COLS);
    printf("总元素数: %d\n", ROWS * COLS);
    printf("内存占用: %.2f MB\n", (ROWS * COLS * sizeof(double) * 3) / (1024.0 * 1024.0));
    
    // 分配矩阵内存
    double** A = allocate_matrix(ROWS, COLS);
    double** B = allocate_matrix(ROWS, COLS);
    double** C_row = allocate_matrix(ROWS, COLS);
    double** C_col = allocate_matrix(ROWS, COLS);
    
    // 生成随机矩阵
    printf("\n生成随机矩阵...\n");
    generate_random_matrix(A, ROWS, COLS);
    generate_random_matrix(B, ROWS, COLS);
    
    // 测试按行相加
    printf("\n测试按行相加...\n");
    clock_t start = clock();
    matrix_add_row_wise(A, B, C_row, ROWS, COLS);
    clock_t end = clock();
    double time_row = ((double)(end - start)) / CLOCKS_PER_SEC;
    printf("按行相加时间: %.6f 秒\n", time_row);
    
    // 测试按列相加
    printf("\n测试按列相加...\n");
    start = clock();
    matrix_add_col_wise(A, B, C_col, ROWS, COLS);
    end = clock();
    double time_col = ((double)(end - start)) / CLOCKS_PER_SEC;
    printf("按列相加时间: %.6f 秒\n", time_col);
    
    printf("按行相加: %.6f 秒\n", time_row);
    printf("按列相加: %.6f 秒\n", time_col);
    printf("时间节省: %.2f%%\n", (time_col - time_row) / time_col * 100);
    
    

    free_matrix(A, ROWS);
    free_matrix(B, ROWS);
    free_matrix(C_row, ROWS);
    free_matrix(C_col, ROWS);
    
    return 0;
}
